<script setup lang="ts">
import { ElInputNumber, ElMessage, ElRow, type FormInstance } from 'element-plus'
import dayjs from 'dayjs'
import { useEntPageData, useInitForm } from '../createHelper'
import { rules } from './page'
import { useAccount, useEnvOrgs, useGetDistricts, useGetNEIndustrys, useOwnerOrgsTree } from '@/utils/dataHook'
import entApi from '@/api/modules/ent'
import useEntStore from '@/store/modules/ent'

const { currentEntData } = storeToRefs(useEntStore())

const router = useRouter()

const { id, isCreate, isReadOnly } = useEntPageData()
const btnLoading = ref(false)

const OwnerList = useOwnerOrgsTree()

const { formData, initForm } = useInitForm()
const formRef = ref<FormInstance>()
const formAccountRef = ref<FormInstance>()
const accountData = useAccount(id.value)
const envOrgs = useEnvOrgs()

watchEffect(() => {
  if (!isCreate.value && currentEntData.value.baseInfo) {
    formData.value = { ...currentEntData.value.baseInfo }
  }
})

onUnmounted(() => {
  formRef.value?.resetFields()
  formAccountRef.value?.resetFields()
  initForm()
})

const industryList = useGetNEIndustrys()
const districts = useGetDistricts()

async function saveAccount(enterpriseObjID: string) {
  await entApi.SetAccount({ enterpriseObjID, accounts: accountData.data })
}

async function create() {
  if (!formRef.value) {
    return
  }
  await formRef.value.validate()
  const data = await entApi.EnterpriseAdd({ enterprise: formData.value })
  data.ObjID && saveAccount(data.ObjID)
  ElMessage.success('创建成功')
  // 更新路由，包含id
  router.replace({
    path: `/document/manager/modify/${data.ObjID}`,
  })
}
async function update() {
  if (!formRef.value) {
    return
  }
  await formRef.value.validate()
  const data = await entApi.EnterpriseUpdate({ enterprise: formData.value, enterpriseObjID: id.value })
  data.InstallDate = dayjs(data.InstallDate).format('YYYY-MM-DD')
  formData.value = data
  data.ObjID && saveAccount(data.ObjID)
  ElMessage.success('保存成功')
}

async function submit() {
  btnLoading.value = true
  await isCreate.value ? create() : update()
  btnLoading.value = false
}

function back() {
  router.back()
}
</script>

<template>
  <div class="mt-10">
    <div>
      <h4>企业信息</h4>
    </div>
    <ElForm ref="formRef" :model="formData" label-width="180px" label-position="top" label-suffix="：" :rules="rules">
      <ElRow :gutter="30">
        <ElCol :span="8">
          <ElFormItem label="企业名称" prop="Name">
            <ElInput v-model="formData.Name" :disabled="isReadOnly" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="统一社会信用代码" prop="CreditCode">
            <ElInput v-model="formData.CreditCode" :disabled="isReadOnly" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="行政区划" prop="DistrictID">
            <el-cascader v-model="formData.DistrictID" :disabled="isReadOnly" :options="districts" class="w-full" :props="{ emitPath: false }" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="管理机构" prop="EnvOrgCode">
            <el-cascader
              v-model="formData.EnvOrgCode" :disabled="isReadOnly" :options="envOrgs" class="w-full" :props="{ emitPath: false,
                                                                                                               children: 'Children',
                                                                                                               label: 'Name',
                                                                                                               value: 'Code' }"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="联系人" prop="ContactName">
            <ElInput v-model="formData.ContactName" :disabled="isReadOnly" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="联系电话" prop="ContactTel">
            <ElInput v-model="formData.ContactTel" :disabled="isReadOnly" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="法人" prop="LegalPerson">
            <ElInput v-model="formData.LegalPerson" :disabled="isReadOnly" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="法人联系电话" prop="LegalPersonTel">
            <ElInput v-model="formData.LegalPersonTel" :disabled="isReadOnly" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="经度" prop="Longitude">
            <ElInputNumber v-model="formData.Longitude" :min="-180" :max="180" :disabled="isReadOnly" class="w-full" :controls="false" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="纬度" prop="Latitude">
            <ElInputNumber v-model="formData.Latitude" :min="-90" :max="90" :disabled="isReadOnly" class="w-full" :controls="false" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="运维公司" prop="OwnerOrgCode">
            <el-cascader
              v-model="formData.OwnerOrgCode" :disabled="isReadOnly" :options="OwnerList" class="w-full" :props="{ emitPath: false }"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="安装日期" prop="InstallDate">
            <ElDatePicker v-model="formData.InstallDate" :disabled="isReadOnly" value-format="YYYY-MM-DD" class="!w-full" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="地址" prop="Address">
            <ElInput v-model="formData.Address" :disabled="isReadOnly" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="行业" prop="NEIndustryCode">
            <el-cascader v-model="formData.NEIndustryCode" :disabled="isReadOnly" :options="industryList" class="w-full" :props="{ emitPath: false }" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
    <div>
      <h4>账号信息</h4>
    </div>
    <ElForm ref="formAccountRef" :model="accountData" label-position="top" class="mb-30px" label-width="180px" label-suffix="：" :rules="rules">
      <ElRow :gutter="40">
        <template v-for="(item, index) in accountData.data" :key="index">
          <ElCol :span="12">
            <ElFormItem :label="`账号${index + 1}`" prop="AccountCode">
              <ElInput v-model="item.AccountCode" :disabled="isReadOnly" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="`密码${index + 1}`" prop="Password">
              <ElInput v-model="item.Password" :disabled="isReadOnly" />
            </ElFormItem>
          </ElCol>
        </template>
      </ElRow>
    </ElForm>
    <FixedActionBar v-if="!isReadOnly">
      <ElButton type="primary" :loading="btnLoading" @click="submit">
        {{ isCreate ? '立即创建' : '立即修改' }}
      </ElButton>
      <ElButton @click="back">
        取消
      </ElButton>
    </FixedActionBar>
  </div>
</template>
